<?php


namespace app\cms\model;


use app\cms\community\lib\QueryModel;
use app\cms\community\lib\utils\nodeSortByGroup;
use app\cms\dto\navInfo;
use iflow\Response;

class navModel extends QueryModel
{
    protected $table = "nav_table";

    /**
     * 获取导航栏列表
     * @return Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getNav(): Response
    {
        $nav = $this->where([
            'status' => 1
        ]) -> select() -> toArray();

        // 菜单排序
        $items = (
            new nodeSortByGroup($nav, 'nav_id')
        ) -> sort() -> getSortNode();

        if (count($items) === 0) {
            return message() -> nodata('暂无导航数据');
        }
        return message() -> success('获取导航数据成功', $items);
    }

    public static function addNavInfo(navInfo $navInfo): Response
    {
        return message() -> success('创建栏目成功', self::create((array) $navInfo) -> toArray());
    }

    public static function changeNavItems(navInfo $navInfo): Response
    {
        $info = (array)$navInfo;
        unset($info['nav_id']);
        $company = static::update($info, [
            'nav_id' => $navInfo -> nav_id
        ]);
        if ($company) {
            return message() -> success('更新导航信息成功', $company -> getChangedData());
        }
        return message() -> update_failed('更新失败');
    }

    public function deleteNav(int $nav_id = 0): Response
    {
        $nav = $this->where([
            'parent_id' => $nav_id
        ]) -> findOrEmpty();

        if ($nav -> isExists()) return message() -> update_failed('该栏目下还有 子栏目无法删除');

        $this -> where([
            'nav_id' => $nav_id
        ]) -> delete();
        return message() -> success('删除栏目成功');
    }
}